﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;

namespace YFIN.Helper.Extension
{
    public static class WcfServiceExtension
    {
        public static void RunWcfService(this Type type, Action action)
        {
            var host = new ServiceHost(type);
            host.Open();
            action();
            if (host.State == CommunicationState.Faulted)
            {
                host.Abort();
            }
            else
            {
                host.Close();
            }
        }

        public static void InvokeWcfClient<TChannel>(
            this Uri uri, Binding binding, Action<TChannel> action)
            where TChannel : class
        {
            var client = ChannelFactory<TChannel>.CreateChannel(binding, new EndpointAddress(uri));
            var co = (ICommunicationObject)client;
            co.Open();
            action(client);
            if (co.State == CommunicationState.Faulted)
            {
                co.Abort();
            }
            else
            {
                co.Close();
            }
        }
    }
}
